import { defineStore } from 'pinia'
import * as api from '@/api/role'

export const roleStore = defineStore('roleStore', {
  state: () => ({
    //角色列表
    roleList: [],
    pagination: {
        page: 1,
        limit: 6,
        total: 0,
      },
  }),
  actions: {
    // 获取角色列表-带分页
    async getRolePage(param) {
      try {
        const params = {
            ...param,
            page: this.pagination.page,
            limit: this.pagination.limit
        }
        const res = await api.getRolePage(params)
        this.roleList = res.list || []
        this.pagination.total = res.total
        return res
      } catch(error) {
        throw error
      }
    },

    async getRoleOne(id) {
      try {
        const res = await api.getRole(id)
        return res
      } catch(error) {
        throw error
      }
    },

    async addRole(dataForm) {
      try {
        const res = await api.addRole(dataForm)
        // console.log(res)
        return res
      } catch(error) {
        throw error
      }
    },

    async editRole(dataForm) {
      try {
        const res = await api.editRole(dataForm)
        return res
      } catch(error) {
        throw error
      }
    },

    async saveRole(dataForm) {
      {
        // console.log(dataForm)
        return dataForm.id ?
              this.editRole(dataForm) :
              this.addRole(dataForm)
      }
    },

    async deleteBatch(ids) {
      try {
        const res = await api.deleteRole(ids)
        console.log(res)
        return res
      } catch(error) {
        throw error
      }
    },

    // 角色和用户的关联
    async getRoleUserPage(params) {
      try {
        const res = await api.getRoleUserPage(params)
        // console.log(res)
        return res
      } catch(error) {
        throw error
      }
    },

    async getRoleUserTree() {
      try {
        const res = await api.getRoleMenu()
        // console.log(res)
        return res  // 返回的是一个数组，包含了所有的用户信息，每个用户信息包括id、username、mobile、gender等字段。
      } catch(error) {
        throw error
      }
    },

    async addRoleUser(id, dataForm) {
      try {
        await api.addRoleUser(id, dataForm)
      } catch(error) {
        throw error
      }
    },

    async deleteRoleUser(id, dataForm) {
      try {
        const res = await api.deleteRoleUser(id, dataForm)
        console.log(res)
        return res
      } catch(error) {
        throw error
      }
    }
  }

})